package admin

import (
	"blogApi/controllers"
	. "blogApi/models"
	"encoding/json"
	"reflect"

	"github.com/syyongx/php2go"
)

/*
 * @Description:
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-11-22 15:04:27
 */

// SystemController 控制器
type SystemController struct {
	controllers.BaseController
}

// ResSystemConfigs 返回的数据
type ResSystemConfigs struct {
	Title string `json:"title"`
	Key   string `json:"key"`
	Value string `json:"value"`
}

// InputData 参数接收器
type SysInputData struct {
	Site_name            string `form:"site_name"`
	Site_url             string `form:"site_url"`
	Site_logo            string `form:"site_logo"`
	Site_icp             string `form:"site_icp"`
	Site_tongji          string `form:"site_tongji"`
	Site_copyright       string `form:"site_copyright"`
	Site_co_name         string `form:"site_co_name"`
	Address              string `form:"address"`
	Map_lat              string `form:"map_lat"`
	Map_lng              string `form:"map_lng"`
	Site_phone           string `form:"site_phone"`
	Site_email           string `form:"site_email"`
	Site_qq              string `form:"site_qq"`
	Site_wechat          string `form:"site_wechat"`
	Seo_title            string `form:"seo_title"`
	Site_seo_keywords    string `form:"site_seo_keywords"`
	Site_seo_description string `form:"site_seo_description"`
}

// Index 获取列表
func (sys *SystemController) Index() {
	list := make([]*ResSystemConfigs, 0)
	Db.Model(&SystemConfigs{}).Select("title", "key", "value").Order("id desc").Find(&list)
	sys.ResJson(0, "操作成功", list, nil)
}

// Save 保存
func (sys *SystemController) Save() {
	if sys.Ctx.Input.IsPost() == false {
		sys.ResJson(1, "请求方式错误", nil, nil)
	}
	var input SysInputData
	// 获取 axios 传递的参数
	data := sys.Ctx.Input.RequestBody
	err := json.Unmarshal(data, &input)
	if err != nil {
		sys.ResJson(1, "存入失败", err.Error(), nil)
	}
	var typeInfo = reflect.TypeOf(input)
	var valInfo = reflect.ValueOf(input)
	num := typeInfo.NumField()
	for i := 0; i < num; i++ {
		// 转化为小写
		key := php2go.Strtolower(typeInfo.Field(i).Name)
		val := valInfo.Field(i).Interface()
		// 条件更新
		result := Db.Model(&SystemConfigs{}).Where("`key` = ?", key).Update("value", val)
		if result.Error != nil {
			sys.ResJson(1, "操作失败", result.Error, nil)
		}
	}
	sys.ResJson(0, "操作成功", nil, nil)
}
